{
  "cells": [
    {
      "cell_type": "raw",
      "id": "afaf8039",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: Tavily Search API\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e49f1e0d",
      "metadata": {},
      "source": [
        "# TavilySearchAPIRetriever\n",
        "\n",
        "[Tavily's Search API](https://tavily.com) is a search engine built specifically for AI agents (LLMs), delivering real-time, accurate, and factual results at speed.\n",
        "\n",
        "## Overview\n",
        "\n",
        "This will help you getting started with the Tavily Search API [retriever](/docs/concepts/retrievers). For detailed documentation of all `TavilySearchAPIRetriever` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_retrievers_tavily_search_api.TavilySearchAPIRetriever.html).\n",
        "\n",
        "### Integration details\n",
        "\n",
        "| Retriever | Source | Package |\n",
        "| :--- | :--- | :---: |\n",
        "[`TavilySearchAPIRetriever`](https://api.js.langchain.com/classes/langchain_community_retrievers_tavily_search_api.TavilySearchAPIRetriever.html) | Information on the web. | [`@langchain/community`](https://npmjs.com/@langchain/community/) |\n",
        "\n",
        "## Setup\n",
        "\n",
        "You will need to populate a `TAVILY_API_KEY` environment variable with your Tavily API key or pass it into the constructor as `apiKey`. Obtain a key by signing up [on their website](https://tavily.com/).\n",
        "\n",
        "If you want to get automated tracing from individual queries, you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "```typescript\n",
        "// process.env.LANGSMITH_API_KEY = \"<YOUR API KEY HERE>\";\n",
        "// process.env.LANGSMITH_TRACING = \"true\";\n",
        "```\n",
        "\n",
        "### Installation\n",
        "\n",
        "This retriever lives in the `@langchain/community` package:\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/community @langchain/core\n",
        "</Npm2Yarn>\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a38cde65-254d-4219-a441-068766c0d4b5",
      "metadata": {},
      "source": [
        "## Instantiation\n",
        "\n",
        "Now we can instantiate our retriever:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "70cc8e65-2a02-408a-bbc6-8ef649057d82",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { TavilySearchAPIRetriever } from \"@langchain/community/retrievers/tavily_search_api\";\n",
        "\n",
        "const retriever = new TavilySearchAPIRetriever({\n",
        "  k: 3,\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c9da7fc7",
      "metadata": {},
      "source": [
        "For a full list of allowed arguments, see [the official documentation](https://docs.tavily.com/docs/tavily-api/rest_api#parameters). You can pass any param to the SDK via a `kwargs` object."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5c5f2839-4020-424e-9fc9-07777eede442",
      "metadata": {},
      "source": [
        "## Usage"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "51a60dbe-9f2e-4e04-bb62-23968f17164a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  Document {\n",
            "    pageContent: \"{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1722900266, 'localtime': '2024-08-05 16:24'}, 'current': {'last_updated_epoch': 1722899700, 'last_updated': '2024-08-05 16:15', 'temp_c': 16.8, 'temp_f': 62.2, 'is_day': 1, 'condition': {'text': 'Partly Cloudy', 'icon': '//cdn.weatherapi.com/weather/64x64/day/116.png', 'code': 1003}, 'wind_mph': 13.2, 'wind_kph': 21.2, 'wind_degree': 261, 'wind_dir': 'W', 'pressure_mb': 1014.0, 'pressure_in': 29.94, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 74, 'cloud': 60, 'feelslike_c': 16.8, 'feelslike_f': 62.2, 'windchill_c': 16.8, 'windchill_f': 62.2, 'heatindex_c': 16.8, 'heatindex_f': 62.2, 'dewpoint_c': 12.3, 'dewpoint_f': 54.1, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 5.0, 'gust_mph': 17.3, 'gust_kph': 27.8}}\",\n",
            "    metadata: {\n",
            "      title: 'Weather in San Francisco',\n",
            "      source: 'https://www.weatherapi.com/',\n",
            "      score: 0.9947009,\n",
            "      images: []\n",
            "    },\n",
            "    id: undefined\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: 'Current Weather for Popular Cities . San Francisco, CA 56 ° F Mostly Cloudy; Manhattan, NY warning 85 ° F Fair; Schiller Park, IL (60176) 71 ° F Mostly Cloudy; Boston, MA warning 84 ° F Partly ...',\n",
            "    metadata: {\n",
            "      title: 'San Francisco, CA Hourly Weather Forecast | Weather Underground',\n",
            "      source: 'https://www.wunderground.com/hourly/us/ca/san-francisco/date/2024-08-02',\n",
            "      score: 0.9859904,\n",
            "      images: []\n",
            "    },\n",
            "    id: undefined\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: 'San Francisco CA 37.77°N 122.41°W (Elev. 131 ft) Last Update: 2:42 pm PDT Aug 4, 2024. Forecast Valid: 5pm PDT Aug 4, 2024-6pm PDT Aug 11, 2024 . Forecast Discussion . Additional Resources. Radar & Satellite Image. Hourly Weather Forecast. ... Severe Weather ; Current Outlook Maps ; Drought ; Fire Weather ; Fronts/Precipitation Maps ; Current ...',\n",
            "    metadata: {\n",
            "      title: 'National Weather Service',\n",
            "      source: 'https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA',\n",
            "      score: 0.98141783,\n",
            "      images: []\n",
            "    },\n",
            "    id: undefined\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const query = \"what is the current weather in SF?\";\n",
        "\n",
        "await retriever.invoke(query);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dfe8aad4-8626-4330-98a9-7ea1ca5d2e0e",
      "metadata": {},
      "source": [
        "## Use within a chain\n",
        "\n",
        "Like other retrievers, `TavilySearchAPIRetriever` can be incorporated into LLM applications via [chains](/docs/how_to/sequence/).\n",
        "\n",
        "We will need a LLM or chat model:\n",
        "\n",
        "```{=mdx}\n",
        "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
        "\n",
        "<ChatModelTabs customVarName=\"llm\" />\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "25b647a3-f8f2-4541-a289-7a241e43f9df",
      "metadata": {},
      "outputs": [],
      "source": [
        "// @lc-docs-hide-cell\n",
        "\n",
        "import { ChatOpenAI } from \"@langchain/openai\";\n",
        "\n",
        "const llm = new ChatOpenAI({\n",
        "  model: \"gpt-4o-mini\",\n",
        "  temperature: 0,\n",
        "});"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "23e11cc9-abd6-4855-a7eb-799f45ca01ae",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "import { RunnablePassthrough, RunnableSequence } from \"@langchain/core/runnables\";\n",
        "import { StringOutputParser } from \"@langchain/core/output_parsers\";\n",
        "\n",
        "import type { Document } from \"@langchain/core/documents\";\n",
        "\n",
        "const prompt = ChatPromptTemplate.fromTemplate(`\n",
        "Answer the question based only on the context provided.\n",
        "\n",
        "Context: {context}\n",
        "\n",
        "Question: {question}`);\n",
        "\n",
        "const formatDocs = (docs: Document[]) => {\n",
        "  return docs.map((doc) => doc.pageContent).join(\"\\n\\n\");\n",
        "}\n",
        "\n",
        "// See https://js.langchain.com/docs/tutorials/rag\n",
        "const ragChain = RunnableSequence.from([\n",
        "  {\n",
        "    context: retriever.pipe(formatDocs),\n",
        "    question: new RunnablePassthrough(),\n",
        "  },\n",
        "  prompt,\n",
        "  llm,\n",
        "  new StringOutputParser(),\n",
        "]);"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "d47c37dd-5c11-416c-a3b6-bec413cd70e8",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The current weather in San Francisco is partly cloudy with a temperature of 16.8°C (62.2°F). The wind is coming from the west at 13.2 mph (21.2 kph), and the humidity is at 74%. There is no precipitation, and visibility is 10 km (6 miles).\n"
          ]
        }
      ],
      "source": [
        "await ragChain.invoke(query);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a5bb5ca-c3ae-4a58-be67-2cd18574b9a3",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all `TavilySearchAPIRetriever` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_retrievers_tavily_search_api.TavilySearchAPIRetriever.html)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
